import React, { memo, useEffect, useState } from 'react';
import { Form, Input, Modal, Select, message } from 'antd';
import {
    queryStaffRelativeKeyList,
    onAddStaffInfo,
    onEditSalaryItemSimple
} from '@/services/salaryManage/salaryCalculate';
import LimitInput from '@/components/LimitInput';
import { COMMON_NAME } from '@/pages/SalaryManage/utils';
import styles from '../../index.less';

const { Option } = Select;

const AddStaffInfoModal = ({
    visible = true,
    type = 'add',
    editData = {},
    onChange,
    onCancel,
    form,
    currentOrgCode
}) => {
    const { getFieldDecorator, validateFields } = form;
    const [dictList, setDictList] = useState([]);
    const [loading, setLoading] = useState(false);
    const formItemLayout = {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 7 }
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 17 }
        }
    };
    const getDict = async () => {
        try {
            const { code, data, msg } = await queryStaffRelativeKeyList(currentOrgCode, 1);
            console.log('取值关联字段数据', data);
            if (code === 10000) {
                setDictList(data);
            } else {
                message.error(msg);
            }
        } catch (e) {
            console.log(e);
        }
    };

    // 取值关联字段变更时
    const onChangeStaffInfo = function onChangeStaffInfo(value, option) {
        const text = value ? option.props.children?.trim() : '';

        if (text) {
            form.setFieldsValue({ itemName: text });
        }
    };

    useEffect(() => {
        getDict();
    }, []);
    return (
        <Modal
            title={type === 'add' ? '新增员工基础信息' : '编辑员工基础信息'}
            visible={visible}
            confirmLoading={loading}
            width={640}
            className={styles.formModal}
            onOk={() => {
                validateFields(async (err, values) => {
                    console.log(values);
                    try {
                        if (!err) {
                            console.log('Received values of form: ', values);
                            setLoading(true);
                            const params = {
                                ...editData,
                                organizationCode: currentOrgCode,
                                ...values
                            };
                            if (type === 'edit') {
                                params.id = editData.id;
                            }
                            const { code, msg = '操作失败，请检查！' } =
                                type === 'add' ? await onAddStaffInfo(params) : await onEditSalaryItemSimple(params);
                            if (code === 10000) {
                                onChange();
                                message.success('操作成功！');
                            } else {
                                message.error(msg);
                            }
                            setLoading(false);
                        }
                    } catch (e) {
                        console.log(e);
                        setLoading(false);
                    }
                });
            }}
            onCancel={onCancel}
            destroyOnClose
        >
            <Form {...formItemLayout}>
                <Form.Item label="设置类型">
                    {getFieldDecorator('itemType', {
                        initialValue: 1
                    })(
                        <Select disabled>
                            <Option value={1}>员工基础信息</Option>
                        </Select>
                    )}
                </Form.Item>
                <Form.Item label="取值关联字段">
                    {getFieldDecorator('staffInfoId', {
                        initialValue: editData.staffInfoId,
                        rules: [
                            {
                                required: true,
                                message: '请选择取值关联字段'
                            }
                        ]
                    })(
                        <Select
                            placeholder="请选择"
                            disabled={type === 'edit'}
                            showSearch
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            onChange={onChangeStaffInfo}
                        >
                            {dictList
                                .filter(item => !item.used || item.key === editData.staffInfoId)
                                .map(item => (
                                    <Option value={item.key} key={item.value}>
                                        {item.value}
                                    </Option>
                                ))}
                        </Select>
                    )}
                </Form.Item>
                <Form.Item label="基础信息名称">
                    {getFieldDecorator('itemName', {
                        initialValue: editData.itemName || '',
                        rules: [
                            {
                                required: true,
                                message: '请输入基础信息名称'
                            },
                            {
                                max: 100,
                                message: '不能超过100个字符'
                            },
                            {
                                pattern: COMMON_NAME.REG,
                                message: COMMON_NAME.MESSAGE
                            }
                        ]
                    })(<Input placeholder="请输入基础信息名称" maxLength={100} />)}
                </Form.Item>
                <Form.Item label="备注说明">
                    {getFieldDecorator('remark', {
                        initialValue: editData.remark || '',
                        rules: [
                            {
                                max: 500,
                                message: '不能超过500个字符'
                            }
                        ]
                    })(<LimitInput placeholder="请输入备注说明" maxLength={500} area showNumber />)}
                </Form.Item>
            </Form>
        </Modal>
    );
};
export default memo(Form.create({ name: 'addStaffInfoModal' })(AddStaffInfoModal));
